package com.slmxz.tms.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slmxz.tms.common.component.RedisService;
import com.slmxz.tms.common.constant.RedisConstants;
import com.slmxz.tms.common.enums.BizMessageEnum;
import com.slmxz.tms.core.exception.Asserts;
import com.slmxz.tms.core.security.util.SecurityUtils;
import com.slmxz.tms.system.converter.ConfigConverter;
import com.slmxz.tms.system.mapper.ConfigMapper;
import com.slmxz.tms.system.model.entity.Config;
import com.slmxz.tms.system.model.form.ConfigForm;
import com.slmxz.tms.system.model.query.ConfigPageQuery;
import com.slmxz.tms.system.model.vo.ConfigVO;
import com.slmxz.tms.system.service.ConfigService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置Service接口实现
 * @author sunyao
 * @Date 2024-11-05
 */
@Service
@RequiredArgsConstructor
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    private final ConfigConverter configConverter;

    /**
     * 系统启动完成后，加载系统配置到缓存
     */
    @PostConstruct
    public void init() {
        refreshCache();
    }


    @Override
    public IPage<ConfigVO> selectPage(IPage<ConfigVO> page, ConfigVO config) {
        return page.setRecords(this.baseMapper.selectPage(page,config));
    }

    /**
     * 保存系统配置
     *
     * @param configForm 系统配置表单
     * @return 是否保存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(ConfigForm configForm) {
        Assert.isTrue(
                super.count(new LambdaQueryWrapper<Config>().eq(Config::getConfigKey, configForm.getConfigKey())) == 0,
                "配置键已存在");
        Config config = BeanUtil.copyProperties(configForm, Config.class);
        this.save(config);
        // 刷新缓存
        refreshCache();
        return true;
    }

    /**
     * 获取系统配置表单数据
     *
     * @param id 系统配置ID
     * @return 系统配置表单数据
     */
    @Override
    public ConfigForm getConfigFormData(Long id) {
        Config entity = this.getById(id);
        return configConverter.toForm(entity);
    }

    @Override
    public String selectConfigByKey(String configKey) {
        QueryWrapper<Config> configQuery = new QueryWrapper<>();
        configQuery.lambda().eq(Config::getConfigKey,configKey);
        Config config = this.getOne(configQuery);
        if(config == null){
            return null;
        }
        return config.getConfigValue();
    }

    /**
     * 编辑系统配置
     *
     * @param configForm 系统配置表单
     * @return 是否编辑成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit( ConfigForm configForm) {
        Assert.isTrue(
                super.count(new LambdaQueryWrapper<Config>().eq(Config::getConfigKey, configForm.getConfigKey())
                        .ne(Config::getId, configForm.getId())) == 0,
                "配置键已存在");
        Config config = configConverter.toEntity(configForm);
        config.setUpdateBy(SecurityUtils.getUserId());
        this.updateById(config);
        // 刷新缓存
        refreshCache();
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String ids) {
        //请求的参数是空的
        Asserts.fail(StrUtil.isBlank(ids), BizMessageEnum.PARAM_IS_NULL);
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();

        this.baseMapper.deleteBatchIds(idList);
        // 刷新缓存
        refreshCache();
        return true;
    }

    /**
     * 刷新系统配置缓存
     *
     * @return 是否刷新成功
     */
    @Override
    public boolean refreshCache() {
        RedisService.del(RedisConstants.SYSTEM_CONFIG_KEY);
        List<Config> list = this.list();
        if (list != null) {
            Map<String, String> map = list.stream().collect(Collectors.toMap(Config::getConfigKey, Config::getConfigValue));
            RedisService.hSetAll(RedisConstants.SYSTEM_CONFIG_KEY, map);
            return true;
        }
        return false;
    }

    /**
     * 获取系统配置
     *
     * @param key 配置键
     * @return 配置值
     */
    @Override
    public Object getSystemConfig(String key) {
        if (StringUtils.isNotBlank(key)) {
            return RedisService.hGet(RedisConstants.SYSTEM_CONFIG_KEY, key);
        }
        return null;
    }

}
